package com.haixee.parkdemo.auth.controller;

import com.haixee.parkdemo.auth.entity.dto.AdminLoginDTO;
import com.haixee.parkdemo.auth.entity.request.AdminRequest;
import com.haixee.parkdemo.auth.entity.request.AuthRequest;
import com.haixee.parkdemo.auth.model.DataScope;
import com.haixee.parkdemo.auth.model.FieldRule;
import com.haixee.parkdemo.auth.model.User;
import com.haixee.parkdemo.auth.service.*;
import com.haixee.parkdemo.common.response.ResResult;
import com.haixee.parkdemo.common.response.ResUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
@RequestMapping("/rpc")
public class RPCController {

    @Autowired
    private DataAccessService dataAccessService;

    @Autowired
    private OrganizeService organizeService;

    @Autowired
    private UserService userService;

    @Autowired
    private GroupService groupService;

    @Autowired
    private AdminService adminService;

    @GetMapping("/data/scope")
    public DataScope getDataScope(Integer aclId) {
        return dataAccessService.getByAclId(aclId);
    }

    @GetMapping("/data/field/rule")
    public Map<String, List<FieldRule>> getFieldRule(Integer aclId, String[] fieldNameList) {

        Map<String, List<FieldRule>> result = new HashMap<>();
        List<FieldRule> fieldRules = dataAccessService.getFieldRules(aclId, Arrays.asList(fieldNameList));
        for (FieldRule fieldRule : fieldRules) {
            String name = fieldRule.getFieldName();
            List<FieldRule> fieldRuleList = result.computeIfAbsent(name, k -> new ArrayList<>());
            fieldRuleList.add(fieldRule);
        }

        return result;
    }

    @PostMapping("/user/acls")
    public ResResult haveAuth(@RequestBody AuthRequest request) {
        return ResUtil.success(userService.hasAcl(request.getToken(), request.getMethod(), request.getRouter()));
    }

    @GetMapping("/organize/under_tree")
    public List<Integer> organizeUnderTree(Integer uid) {
        return organizeService.getUnderTree(uid);
    }

    @GetMapping("/group/under_tree")
    public Set<Integer> groupUnderTree(Integer uid) {

        return groupService.getUnderTreeByUid(uid);
    }

    @GetMapping("/user")
    public User getUser(Integer uid) {
        return userService.getUser(uid);
    }

    @PostMapping("/login")
    public ResResult login(@RequestBody AdminRequest request) {

        AdminLoginDTO data = adminService.getAdminLogin(request.getUsername(), request.getPassword());

        return ResUtil.success(data);
    }
}
